package com.chy.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chy.common.CustomException;
import com.chy.entity.Category;
import com.chy.mapper.CategoryMapper;
import com.chy.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;

    @Override
    public boolean updateById(Category category) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getName, category.getName()).ne(Category::getId, category.getId());
        Category one = this.getOne(wrapper);
        if(one != null) {
            throw new CustomException("分类名称已存在！");
        }
        return super.updateById(category);
    }
    @Override
    public boolean save(Category category) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getName, category.getName());
        Category one = this.getOne(wrapper);
        if(one != null) {
            throw new CustomException("分类名称已存在！");
        }
        return super.save(category);
    }

    @Override
    public List<Category> getAllCategoryList(Map<String, Object> params) {
        String s = JSON.toJSONString(params);
        Category category = JSON.parseObject(s, Category.class);
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(category.getName() != null, Category::getName, category.getName());
        List<Category> list = categoryMapper.selectList(wrapper);
        return list;
    }
}
